<template>
  <div id="view">
    <div class="w1200">
      <p class="guide">
        <router-link to="/machinemarket">算力市场&nbsp;&nbsp;>&nbsp;</router-link>
        <span>订单总览</span>
      </p>
      <div id="pageContent">
        <p class="location">订单总览</p>
        <section id="sec1">
          <div class="cl">
            <span>
              <span class="name">名称:</span>
              <span class="message">{{machine.name}}</span>
            </span>
            <span>
              <span class="name">基础算力:</span>
              <span class="message">{{machine.base_power}}T</span>
            </span>
            <span>
              <span class="name">浮动算力:</span>
              <span class="message">{{machine.float_power}}T</span>
            </span>
            <span v-if="machine.bhp_power > 0">
              <span>BHP参配算力:</span>
              <span>{{machine.bhp_power}}T</span>
            </span>
          </div>
          <div class="cl">
            <span>
              <span class="name">期货算力:</span>
              <span class="message">{{machine.futures_power}}T</span>
            </span>
            <span>
              <span class="name">定期算力:</span>
              <span class="message">{{machine.regular_power}}T</span>
            </span>
            <span>
              <span class="name">单价:</span>
              <span class="message">{{unitPirce}}{{selectedPayType}}</span>
            </span>
            <span>
              <span class="name">合约类型:</span>
              <span class="message">BTC</span>
            </span>
          </div>
          <div class="cl">
            <span>
              <span class="name">合约期限:</span>
              <span class="message">{{machine.regular_date_num}}天</span>
            </span>
            <span>
              <span class="name">开挖时间:</span>
              <span class="message">{{machine.time_income}}</span>
            </span>
            <span>
              <span class="name">算力来源:</span>
              <span class="message">{{machine.power_node_name}}</span>
            </span>
          </div>
        </section>
        <section id="sec2">
          <p class="p1">
            <span class="name">购买份额:</span>
            <input type="number" placeholder="" @input="numChange()"  @blur="outInput()" v-model="num">
            <span>份</span>
          </p>
          <p class="p2 payType">
            <span class="name">选择支付方式:</span>
            <span class="allTypes">
              <span v-for="(item , index) in pay_channel" :class="selectedPayType == item.pay_currency ? 'active' : ''"
                    @click="chosePayType( item.pay_currency , item.payUnit)">
                {{item.pay_currency}}
              </span>
            </span>
          </p>
          <p class="p3">
            <span class="name">可用余额：</span>
            <span>{{asset[selectedPayType]}}{{selectedPayType}}</span>
          </p>
        </section>
        <section id="sec3">
          <p class="p1">总计</p>
          <div class="p2">
            <span>
               <span class="introduce">
                 <span class="span1">到手总算力</span>
                 <img src="../common/imgs/explain2.png" alt="" class="btnImg hoverhand">
                 <span class="powerList boxshadow">
                <span>
                  <span>基础算力</span><span>{{powerList.base_power}}T</span>
                </span>
                  <span>
                  <span>浮动算力</span><span>{{powerList.float_power}}T</span>
                </span>
                  <span>
                  <span>达标算力</span><span>{{powerList.pe_power}}T</span>
                </span>
                <span>
                  <span>期货算力</span><span>{{powerList.futures_power}}T</span>
                </span>
                  <span>
                  <span>定期算力</span><span>{{powerList.regular_power}}T</span>
                </span>
              </span>
               </span>
              <span class="span2">{{handsPower}}{{machine.unit_name}}</span>
            </span>
            <span class="bhpPower" v-if="machine && Number(machine.bhp_power) > 0">
               <span class="introduce">
                 <span class="span1">到手BHP总算力</span>
                <!-- <img src="../common/imgs/explain2.png" alt="" class="btnImg hoverhand"> -->
               </span>
              <span class="span2">{{totalBhpPower}}{{machine.unit_name}}</span>
            </span>
            <span>
               <span class="introduce">
                 <span class="span1">总金额</span>
               </span>
              <span class="span2">{{lastTotalMoney}}{{selectedPayType}}</span>
            </span>
          </div>
          <div class="p3">
            <label for="agree">
              <input type="checkbox" id="agree" v-model="agree">
              <span>我同意</span>
            </label>
            <span class="agreement" v-for="(item , index) in contract" @click="showAgreement(item.code)">《{{item.name}}》</span>
          </div>
          <div class="p4">
            <button id="justPay" @click="justPay()">立即支付</button>
            <span :id="tdspan" class="tdspan hoverhand" v-show="is_tongdun_on == 1 && showTd"></span>
          </div>
        </section>
      </div>
    </div>
     <agree-ment ref="ag" hasReadText="已阅读此协议" @isRead=""/>
     <confirm-dialog ref="buyConfirm" msg="确定购买此订单？" @confirm="confirmBuy"/>
  </div>
</template>
<script>
  import {   getMachineDetail , orderAgreement , orderRent } from "../http/api";
  export default {
    name: 'classicMachineDetail',
    data() {
      return {
        machine_id : '',//矿机id
        machine: {}, //矿机信息
        tdspan:'td' + Math.floor(Math.random()*(1-10000) + 10000), //同盾绑定id
        yzm_token :'',//同盾TOKEN
        blackBox:'',//同盾getInfo,
        showTd : true,//页面判断同盾显示条件
        reset:'',//同盾重载方法
        is_tongdun_on : 0,//是否开启同盾
        pay_channel : [],//支付方式 包括余额
        selectedPayType : '',//选择的支付方式
        asset : [],//余额
        num : '',//购买份数
        lastTotalMoney : '',//最终需支付金额
        minNum : '',//最低购买数量
        maxNum : '',//最大购买数量
        handsPower : '',//到手总算力
        totalBhpPower : '',//到手bhp总算力
        contract : [],//协议
        unitPirce : '',//单价
        agree : false,//是否同意协议
        powerList:{
          base_power : 0,
          float_power : 0,
          pe_power : 0,
          futures_power : 0,
          regular_power : 0,
        }
      }
    },
    components:{
      tongdunCountdown: resolve => { require(['../components/tongdunCountdown'], resolve) },//同盾倒计时功能插件
      AgreeMent: resolve => { require(['../components/AgreementDialog'], resolve) },//协议弹窗
      ConfirmDialog: resolve => { require(['../components/ConfirmDialog'], resolve) },//确认弹窗
    },
    mounted() {
      let machine_id = this.$route.query.machine_id , thiz = this;
      this.machine_id = machine_id;
      getMachineDetail({   machine_id: machine_id }).then(res => {
        let data = res.data;
        let machine = data.machine;
        this.contract = machine.contract;//协议
        let pay_channel = machine.pay_channel;//支付方式
        let good_deposit = machine.good_deposit;//价格
        if(good_deposit.length === 1){
          for( let i = pay_channel.length-1 ; i >= 0; i--){
            let item = pay_channel[i];
            if( item === 'RRM_USDT'){
              pay_channel = thiz.arrRemove( pay_channel , i);
              break;
            }
          }
        }
        this.pay_channel = pay_channel;//支付方式 ，组装进余额
        this.machine = machine;
        this.maxNum = machine.maxLimitNum;//最大购买数量
        this.minNum = machine.minLimitNum;//最低购买数量
        this.num = this.minNum;
        this.packagePayArr(data);
        let is_tongdun_on = machine.is_tongdun_on;//是否开启同盾;
        thiz.is_tongdun_on = is_tongdun_on;
        if( is_tongdun_on == 1 ){
          thiz.openTongdun();// 判断是否需要开起同盾
        }
      });
    },
    methods: {
      packagePayArr(data){
        let asset = data.asset;
        console.log('data.machine',data.machine)
        let good_deposit = data.machine.good_deposit;
        this.asset = asset;
        let pay_channel = this.pay_channel;
        // console.log('pay_channel',pay_channel)
        this.for(pay_channel , (item ,index) => {
          let itemType = { payUnit : item };
          switch (item) {
            case "RRM_CASH":
              itemType.pay_currency = 'CNY';//币种名称
              itemType.balance = asset.CNY;//余额
              break;
            case 'RRM_USDT':
              itemType.pay_currency = 'USDT';
              itemType.balance = asset.USDT;
              break;
            case 'RRM_BCNY':
              itemType.pay_currency = 'BCNY';
              itemType.balance = asset.BCNY;
              break;
          }
          this.for(good_deposit , (item , index) => {
            if(itemType.pay_currency === item.pay_currency){
               itemType.goods_deposit = item.goods_deposit; //单价
            }
          })
          pay_channel[index] = itemType;
        });
        this.pay_channel = pay_channel;
        this.selectedPayType = pay_channel[0].pay_currency;
      },
      chosePayType(pay_currency , payUnit){
        this.selectedPayType = pay_currency;
      },
      numChange(){
        //数量变化
        let pay_channel = this.pay_channel;//支付方式、余额
        let selectedPayType = this.selectedPayType;//选择的支付方式
        let unitPirce = 3000 ;// 单价
        this.for(pay_channel , (item , index) => {
          if(selectedPayType === item.pay_currency){
            unitPirce = item.goods_deposit;
          }
        });
        if (this.num) {
          this.num = parseInt(this.num) || this.minNum;
          if (this.num >= this.maxNum) {
            this.num = this.maxNum
          }
          this.lastTotalMoney = this.accMul(unitPirce, this.num ,0);//总支付金额
        } else {
          this.lastTotalMoney = this.accMul(unitPirce, this.minNum ,0);
        }
      },
      outInput(){
        //失去焦点 输入框
        this.num = parseInt(this.num) || this.minNum;
        if (this.num <= this.minNum) {
          this.num = this.minNum
        }
      },
      justPay(){
        let errorInfo = null;
        let num = this.num;
        if(!num || num < this.minNum || num > this.maxNum){
          errorInfo = '请输入正确购买份额';
        }else if( !this.agree ){
          errorInfo = '请同意协议';
        }
        if( errorInfo ){
          require('../common/js/toast').toast(errorInfo);
          return;
        }
        let balance = Number(this.asset[this.selectedPayType]);//可用余额
        let lastTotalMoney = Number(this.lastTotalMoney);//最终支付金额
        console.log('balance',balance);
        console.log('lastTotalMoney',lastTotalMoney);
        let thiz = this;
        if( lastTotalMoney > balance){
          require('../common/js/toast').toast(thiz.selectedPayType+'余额不足');
        }else{
          this.$refs.buyConfirm.dialogShow();
        }
      },
      confirmBuy(){
        /*弹窗确认下单*/
        let thiz = this;
        let payArr = thiz.pay_channel;
        let chosePayUnit = null;
        thiz.for( payArr, (item ,index) => {
          if( item.pay_currency === thiz.selectedPayType ){
            chosePayUnit = item.payUnit;
          }
        });
        let params = {
          machine_id : thiz.machine_id ,
          num : thiz.num ,
          pay_channel : chosePayUnit
        };
        if( thiz.yzm_token ){
          params.yzm_token = thiz.yzm_token;
          params.blackBox = thiz.blackBox;
        }
        orderRent(params).then( res => {
          if( res.code == 200 ){
            require('../common/js/toast').toast('下单成功!');
            this.$router.push({ path : '/paymentSuccessful' , query: {
              orderId : res.data,
              payMoney : thiz.lastTotalMoney,
              payUnit : thiz.selectedPayType,
            }})
          } else{
            if( thiz.is_tongdun_on == 1){
               thiz.showTd = true;
               thiz.reset();
            }
          }
        });
      },
      openTongdun( bl ){
        //开起同盾
        let tdPublic = require('../common/js/tongdun').default;
        let thiz = this;
        let params = {
          display : 'popup',
          container: '#' + thiz.tdspan,
          width: '300px',
          height: '46px',
          beforeValidate : function () {
            // if( !thiz.num ){
            //   require('../common/js/toast').toast('请输入下单数量');
            //   return false
            // }else{
            //   return true;
            // }
          }
        };
        tdPublic(params, function (ret) {
          thiz.showTd = false;
          thiz.yzm_token = ret.validateToken;
          thiz.blackBox = ret.blackBox;
          thiz.reset = ret.reset;//获取重载同盾方法
          // console.log('获取同盾token');
        });
      },
      showAgreement( code ) {
        /*查看协议*/
        let thiz = this,
          params = {
            machine_id : thiz.machine.machine_id,
            code : code,
            currency : thiz.selectedPayType,
            num : thiz.num
         };
        orderAgreement(params).then(res => {
          if( res.code == 200 ){
            thiz.$refs.ag.agreement( res.data.contact.content );
          }
        });
      },
    },
    watch:{
      num(val){
        this.numChange();
        val = val || this.minNum;
        let machine = this.machine;
        let powerList = {
          base_power : machine.base_power,
          float_power : machine.float_power,
          pe_power : 0,
          futures_power : machine.futures_power,
          regular_power : machine.regular_power,
        };
        let handsPower = 0;//到手总算力
        let thiz = this;
        this.for( powerList , (item , key) => {
          let itemPower = thiz.accMul(item , val);
          powerList[key] = itemPower;
          handsPower = thiz.accAddMore( handsPower , itemPower);
        });
        this.handsPower = handsPower;
        this.powerList = powerList;
        this.totalBhpPower = Number(thiz.machine.bhp_power) > 0 ? thiz.accMul(thiz.machine.bhp_power , thiz.num || thiz.minNum) : 0;
      },
      selectedPayType(val){
        this.numChange();
        let good_deposit = this.machine.good_deposit;//支付 单价
        let thiz = this;
        this.for( good_deposit , (item , index) => {
          if(item.pay_currency === val){
            thiz.unitPirce = Number(item.goods_deposit);//单价
          }
        });
      }
    }
  }
</script>
<style lang="less" scoped>
  @import "../common/style/common";
  @import "../common/style/public.css";
  #view{
    padding-top: 72px;padding-bottom: 90px;
  }
  .guide{
    padding: 21px 0;font-size: 16px;
    >a{
      .colorYellow;
    }
    >span{
      color: #262626;
    }
  }
  #pageContent{
    padding: 29px 26px;background: #fff;.borderRadius;padding-bottom: 66px;
    .location{
      color: #262626;font-size: 24px;;
    }
    #sec1{
      padding-top: 44px;;
      .cl{
        overflow: hidden;height: 59px;border-bottom: 1px solid#EEEEEE;
        >span{
          float: left;font-size: 16px;
          >.name{
            color: #262626;
          }
          >.message{
            color: #262626a6;
          }
          >span{
            line-height: 59px;;
          }
        }
        >span:first-child{
           width: 308px;;
        }
        >span:nth-child(2){
          width: 376px;;
        }
        >span:nth-child(3){
          width: 303px;;
        }
      }
    }
    #sec2{
      >p{
        >.name{
          color: #262626;font-size: 16px;display: inline-block;line-height: 38px;;
        }
      }
      >.p1,>.p2{
        padding-top: 32px;overflow: hidden;
      }
      >.p1>.name,>.p2>.name{
          width: 135px;
      }
      >.p1{
        >span{
          float: left;
        }
        >input{
          .input;width:141px;height: 38px;float: left;text-align: center;border-color: #D2D2D2;
        }
        >span:last-child{
          padding-left: 13px;line-height: 38px;
        }
      }
      >.p2{
        overflow: hidden;
        >span{
          float: left;
        }
        >.allTypes{
          overflow: hidden;
          >span{
            height: 38px;display: inline-block;width: 141px;margin-left: 11px;.borderRadius;text-align: center;line-height: 38px;
            font-size: 16px;color: #26262691;border: 1px solid#D2D2D2;
            &:first-child{
              margin-left: 0;
            }
            &:hover{
              cursor: pointer;
            }
            &.active{
              .borderYellow;background: #ffab3229;color: #FFAB32;
            }
          }
        }
      }
      >.p3{
        padding-top: 46px;font-size: 16px;
        >.name{
          line-height: 103%;
        }
      }
    }
    #sec3{
      padding-top: 62px;
      >.p1{
       color: #2626269e;font-size: 16px;padding-bottom: 22px;
      }
      >.p2{
        height: 99px;background: #F7F9FA;border-top: 1px solid#E5E5E5;border-bottom: 1px solid#E5E5E5;padding-left: 20px;
        >span{
          float: left;
          &.bhpPower{
            padding-left: 30px;
            .introduce{
              padding-right: 20px;
            }
          }
          &:last-child{
            padding-left: 65px;
            >.span2{
              padding-left: 14px;
            }
          }
          >span{
            line-height: 99px;height: 99px;display: inline-block;
          }
          .introduce{
            float: left;position: relative;
            >.span1{
              vertical-align: middle;line-height: 107px;
            }
            >.btnImg{
              vertical-align: sub;margin-right: 25px;
              &:hover + .powerList{
                display: inline-block;
              }
            }
            >.powerList{
              position: absolute;left: calc( 100% - 15px );width: 222px;.borderRadius();background: #fff;z-index: 2;color: #999;
              padding: 24px 20px;padding-bottom: 20px;top: 50%;margin-top:10px;display: inline-block;display: none;
              >span{
                display: inline-block;width: 100%;overflow: hidden;padding-top: 20px;font-size: 14px;
                &:first-child{
                  padding-top: 0;
                }
                >span:first-child{
                  float: left;
                }
                >span:last-child{
                  float: right;
                }
              }
            }
          }
          >.span2{
            font-size: 30px;
          }
        }
      }
      >.p3{
        padding-top: 46px;padding-bottom: 18px;;
        >label{
          position: relative;display: inline-block;
          input{
            opacity: 0;position: absolute;z-index: 1;left: 0;top:0;width: 100%;height: 100%;
            &:hover{
              cursor: pointer;
            }
          }
          >span{
            color: #898989;line-height: 18px;position: relative;padding-left: 25px;display: inline-block;
            &:before{
              .checkBox;border-color: #BFBFBF;width: 18px;height: 18px;box-sizing: border-box;position: absolute;left: 0;top: 50%;margin-top: -9px;
            }
          }
          input:checked+span:before{
            .checked;width: 18px;height: 18px;box-sizing: border-box;position: absolute;left: 0;top: 50%;margin-top: -9px;
          }
        }
        >.agreement{
          .colorYellow;font-size: 14px;line-height: 18px;
          &:hover{
            cursor: pointer;
          }
        }
      }
      >.p4{
        position: relative;
        >#justPay{
          .submit();width: 300px;height: 46px;line-height: 46px;font-size: 18px;
        }
        >.tdspan{
          display: inline-block;width: 300px;height: 46px;position: absolute;left: 0;top:0;z-index: 1;
        }
      }
    }
  }

</style>
